#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <string.h>
#define BUFFERSIZE 1024
#define STAGESIZE 256

void writer(const std::string str,int _pipefd[2])
{
    close(_pipefd[0]);
    write(_pipefd[1],str.c_str(),str.size());
}

void reader(int _pipefd[2],std::string* _receiver)
{
    close(_pipefd[1]);
    char stage[STAGESIZE];
    ssize_t bytesRead = read(_pipefd[0],stage,sizeof(stage));
    if(bytesRead > 0)
    {
        stage[bytesRead] ='\0';
        *_receiver = stage;
    }
}

// 疑问1：多进程的执行次序——由CPU调度器决定

int main()
{
    int pipefd[2];
    int pipeRet = pipe(pipefd);
    if(pipeRet == -1) 
    {
        perror("pipe"); 
        exit(1);
    }
    pid_t pid = fork();
    //子进程
    if(pid == 0)
    {
        pid_t pidOfSub = getpid();
        for(int i = 1;i < 6;i++)
        {
            char wbuffer[BUFFERSIZE];
            snprintf(wbuffer,BUFFERSIZE,"进程号：%d-写入次数：%d\n",pidOfSub,i);
            writer(wbuffer,pipefd);   
        }
        exit(0);
    }

    while(true)
    {
        std::string receiver;
        reader(pipefd,&receiver);
        std::cout<<receiver;
        if(receiver.empty())
        {
            break;
        }
    }

    int pstatus = 0;
    waitpid(pid,&pstatus,0);
    std::cout<<WIFEXITED(pstatus)<<std::endl;
    return 0;
}